# coding: utf-8
import time
from datetime import datetime, timedelta

from functools import wraps
from flask import Blueprint
from flask import url_for
from flask import render_template
from flask import request
from flask import session
from flask import redirect
from flask import flash, get_flashed_messages
from leancloud import Object, Query, User, errors

from tools import logging



agmadmin_view = Blueprint('agmadmin', __name__)

def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if 'user' in session:
            return func(*args, **kwargs)
        else:
            return redirect(url_for('agmadmin.login', next=request.full_path))
    return wrapper
    

@agmadmin_view.route('/')
@login_required
def index(): 
    return 'AgmAdmin, Get!Hi, %s!%s' % (session.get('user', 'Nobody'),
        get_flashed_messages())
        
@agmadmin_view.route('/delcache')
@login_required
def delcache(): 
    from dbModels import delcache
    delcache()
    return 'DelCache Done!'        

@agmadmin_view.route('/getaccesstoken')
@login_required
def getaccess(): 
    from tools.wechatAPI import getaccesstoken
    force = request.args.get('force')
    ret = getaccesstoken(force)
    return ret

@agmadmin_view.route('/test')
@login_required      
def test():
    return 'AgmAdmin, Test, GET! %s' % session.get('user')
    
@agmadmin_view.route('/wechatlog/')
@agmadmin_view.route('/wechatlog/<name>')
@logging.log
@login_required
def wechatuser(name='wechatuser'):
    name2object = {
        'wechatuser': 'WechatUser', 'event': 'Log_Wechat_Event', 
        'message': 'Log_Wechat_Message', 'kfrecord': 'WechatKfLog',
        'agmlog': 'Agm_log', 'kfclick': 'WechatKfOLRecord'}
    objectname = name2object.get(name, 'WechatUser')
    query = Query(Object.extend(objectname))
    query.descending('updatedAt')
    strtointset = {'sex', 'subscribe', 'jf', 'opercode', 'groupid'}
    days = request.args.get('days')
    if days:
        days = int(days)
        dayset = datetime.now() - timedelta(days=days)
        query.greater_than('createdAt', dayset)
    date = request.args.get('date')
    if date:
        date = datetime.strptime(date, '%Y-%m-%d')
        date = date + timedelta(days=1)
        query.greater_than('createdAt', date)
        query.ascending('updatedAt')
    filter = request.args.get('filter')
    if filter and ':' in filter:
        key, value = filter.split(':', 1)
        if key in strtointset:
            try:
                value = int(value)
            except:
                pass
        query.equal_to(key, value)
    limit = request.args.get('limit')
    if limit:
        limit = int(limit)
        query.limit(limit)
    startswith = request.args.get('starts_with')
    if startswith and ':' in startswith:
        key, value = startswith.split(':', 1)
        query.startswith(key, value)
    exists = request.args.get('exists')
    if exists:
        query.exists(exists)
    contains = request.args.get('contains')
    if contains:
        key, value = contains.split(':', 1)
        query.contains(key, value)
    notequalto = request.args.get('notequalto')
    if notequalto:
        key, value = notequalto.split(':', 1)
        if key in strtointset:
            try:
                value = int(value)
            except:
                pass        
        query.not_equal_to(key, value)
    users = query.find()
    unique = request.args.get('unique')    
    if unique:
        users1 = []
        unique = unique.split(':')
        uniqueset = set()
        attrs = set()
        for t in users:
            attrs.update(t._attributes)
            checkname = tuple(t.get(s) for s in unique)
            if checkname not in uniqueset:
                uniqueset.add(checkname)
                users1.append(t)
        if request.args.get('viewtype') == 'table':
             return render_template('agmlogs.html', users=users, logtime=logtime, isinstance=isinstance, list=list, attrs=attrs)
        return render_template('agmusers.html', users=users, logtime=logtime, isinstance=isinstance, list=list)
    if request.args.get('viewtype') == 'table':
        attrs = {}
        for t in users:
            attrs.update(t._attributes)
        return render_template('agmlogs.html', users=users, logtime=logtime, isinstance=isinstance, list=list, attrs=attrs)
        
    return render_template('agmusers.html', users=users, logtime=logtime, isinstance=isinstance, list=list)
    
@agmadmin_view.route('/login', methods=['get', 'post'])
def login():
    USER = 'agm_admin'
    PW = 'agmagm1988'
    if request.method == 'POST':
        user = request.form.get('username')
        pw = request.form.get('password')
        _next = request.args.get('next')
        try:
            user_ = User()
            user_.login(user, pw)
            # session.permanent = True
            if user_.get('role') == 'agmadmin':
                session['user'] = user
            return redirect(_next or url_for('agmadmin.index'))
        except errors.LeanCloudError:
            return redirect(url_for('agmadmin.login'))
        # if request.form.get('username') == USER and request.form.get('password') == PW:                
            # session.permanent = True
            # session['user'] = request.form.get('username') or 'imfunimfun'
            # return redirect(url_for('agmadmin.index'))
        # return redirect(url_for('agmadmin.login'))
    return render_template('agmadmin_login.html')
    
    
@agmadmin_view.route('/logout')    
def logout():
    session.pop('user')
    return redirect(url_for('agmadmin.index'))
    
def logtime(item):
    keys = ['CreateTime', 'subscribe_time', 'time']
    for key in keys:
        if item.get(key):
            return datetime.fromtimestamp(item.get(key)).strftime('%Y-%m-%d %H:%M:%S')  
    return item.created_at.strftime('%Y-%m-%d %H:%M:%S')        
            
@agmadmin_view.route('/wraplogin', methods=['GET', 'POST'])
@logging.log
@logging.agmlog
def wraplogin():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        remember = request.form.get('remember')
        user = User()
        try:
            user.login(username, password)
            if user.get('role'):
                if remember == 'on':
                    session.permanent = True
                else:
                    session.permanent = False
                session['username'] = username
                session['role'] = user.get('role')
        except errors.LeanCloudError:
            return render_template('/wrap_login.html', error=True)
        next_ = request.args.get('next')
        if next_:
            return redirect(next_)
    
    return render_template('/wrap_login.html')
